<template>
  <div class="verify-code-main" @click="focus">
    <div
      class="code-item"
      :class="{ 'code-item-input': item.isInput }"
      v-for="(item, index) in countList"
      :key="index"
    >
      {{ item.num }}
    </div>
  </div>
</template>

<script setup lang="ts">
interface VerifyOption {
  num?: number | string
  isInput: boolean
}

interface Props {
  counts?: number
  type?: 'default' | 'number'
}

const props = withDefaults(defineProps<Props>(), {
  counts: 6,
  type: 'default'
})

const emit = defineEmits(['verifyEvent', 'change'])

const countList = ref<Array<VerifyOption>>(
  Array.from(Array(props.counts), () => ({ num: '', isInput: false }))
)

const count = computed(() => countList.value.map((item) => item.num).join(''))

const focus = () => {
  let flag = true
  for (const item of countList.value) {
    if ((item.num !== '' && flag) || (item.num === '' && !flag)) {
      item.isInput = false
    } else {
      item.isInput = true
      flag = false
    }
  }

  emit('change', count.value)
}

onMounted(() => {
  document.onkeydown = inputCode
})

const inputCode = (e: any) => {
  if (e.keyCode === 8) {
    for (let i = countList.value.length - 1; i >= 0; i--) {
      if (countList.value[i].num) {
        countList.value[i].num = ''
        break
      }
    }
    focus()
  }

  switch (props.type) {
    case 'number':
      if (e.keyCode < 48 || (e.keyCode > 57 && e.keyCode < 96) || e.keyCode > 105) return
      break
    case 'default':
      if (
        e.keyCode < 48 ||
        (e.keyCode > 57 && e.keyCode < 65) ||
        (e.keyCode > 90 && e.keyCode < 96) ||
        e.keyCode > 105
      )
        return
      break
  }

  for (const [index, item] of countList.value.entries()) {
    if (!item.num) {
      item.num = e.key
      focus()

      if (index === props.counts - 1) {
        emit('verifyEvent', count.value)
      }

      break
    }
  }
}
</script>

<style scoped lang="scss">
.verify-code-main {
  display: flex;
  gap: 12px;

  .code-item {
    height: 50px;
    width: 50px;
    border-radius: 5px;
    background: #f8f8f8;
    border: 1px solid #d6d6d6;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28px;
    cursor: text;
    transition: 0.4s;
  }

  .code-item-input {
    &::before {
      content: '';
      height: 20px;
      width: 2px;
      background: #bbb;
      animation: input-line-anim 0.6s linear infinite alternate;
    }
  }

  &:hover,
  &:focus {
    .code-item {
      border-color: $main-color;
    }
  }
}

@keyframes input-line-anim {
  0% {
    opacity: 1;
  }
  30% {
    opacity: 1;
  }
  70% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}
</style>
